<template>
  <view class="app" v-if="currentEnvironment==='wx'||currentEnvironment==='zfb'">


    <view class="pay-page">

      <!-- 商品信息 -->
      <view class="shopping-box">
        <view class="shopping-top">
          <view class="lable-title">商品信息</view>
          <view class="lable-number">共1个</view>
        </view>
        <view class="shopping-list">
          <view class="shopping-item">
            <view class="shopping-img">
              <image src=""></image>
            </view>
            <view class="shopping-info">
              <view class="shopping-hd">
                <view>
                  <view class="shopping-title">{{ getLevelTypeName }}</view>
                  <view class="shopping-title" v-if="levelType!==4">【{{ getLevelTimeTypeName }}】</view>
                </view>
                <view class="shopping-price">￥{{ total_fee / 100 }}</view>
                <view class="shopping-price">x1</view>
              </view>
              <view class="shopping-text">商家会员权益升级，可获取更多功能权限</view>
            </view>
          </view>
        </view>
        <view class="shopping-top cell-list">
          <view class="cell-left">折扣</view>
          <view class="cell-right">{{ ((total_fee / price_original) * 100 / 10).toFixed(1) }}折</view>
        </view>
        <view class="end-price">
          <view class="end-label">实付款</view>
          <view class="end-number">￥{{ total_fee / 100 }}</view>
        </view>
      </view>
      <!-- 订单信息 -->
      <view class="shopping-box">
        <view class="shopping-top">
          <view class="lable-title">订单信息</view>
        </view>
        <view class="shopping-top cell-list">
          <view class="cell-left">订单编号</view>
          <view class="cell-right">{{ out_trade_no }}</view>
        </view>
        <view class="shopping-top cell-list">
          <view class="cell-left">支付方式</view>
          <view class="cell-right">{{ payTypeName }}</view>
        </view>
        <view class="shopping-top cell-list">
          <view class="cell-left">下单时间</view>
          <view class="cell-right">{{ new Date().getTime() | time() }}</view>
        </view>


      </view>
      <view class="footer-box">
        <view class="footer-content">
          <view class="price-box">
            合计:
            <view class="price-text">
              <u-icon name="rmb" :bold="true" color="rgb(245, 54, 22)" size="32rpx"></u-icon>
              {{ total_fee / 100 }}
            </view>
          </view>
          <view class="print-item-entry" style="flex:2;">

            <view class="select-box" style="padding:24rpx 60rpx;border-radius: 14rpx;">
              <!--              <view class="selecet-text">立即支付</view>-->
              <view class="selecet-text" @click="toPay('wxpay')" v-if="currentEnvironment==='wx'">
                直接发起微信支付
              </view>

              <view class="selecet-text" @click="toPay('alipay')" v-else-if="currentEnvironment==='zfb'">
                直接发起支付宝支付
              </view>

              <view class="selecet-text" v-else>请通过微信/支付宝扫码</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!--    <button v-if="h5Env === 'h5-weixin'" @click="getWeiXinJsCode('snsapi_base')">公众号获取openid示例</button>-->
    <uni-pay ref="pay" :adpid="adpid" return-url="/pagesA/pay/orderDetail" logo="/static/logo.png" @success="onSuccess"
             @create="onCreate"></uni-pay>
  </view>

  <view v-else>
    请使用微信或支付宝扫码进入支付
  </view>
</template>

<script>
const API = require('../../utils/api/shops.js').default;
const $ = require('../../utils/api.js');
export default {
  data() {
    return {
      levelType: null,
      getLevelTypeName: "",
      getLevelTimeTypeName: "",
      payTypeName: "",
      currentEnvironment: "",
      shopId: null,
      levelPriceId: null,
      total_fee: 1, // 支付金额，单位分 100 = 1元
      price_original: 1,//原始单价
      order_no: "", // 业务系统订单号（即你自己业务系统的订单表的订单号）
      out_trade_no: "", // 插件支付单号
      description: "", // 支付描述
      type: "", // 支付回调类型 如 recharge 代表余额充值 goods 代表商品订单（可自定义，任意英文单词都可以，只要你在 uni-pay-co/notify/目录下创建对应的 xxx.js文件进行编写对应的回调逻辑即可）
      //qr_code: true, // 是否强制使用扫码支付
      openid: "", // 微信公众号需要
      custom: {},
      adpid: "1000000001", // uni-ad的广告位id
    }
  },
  onLoad(options = {}) {
    this.getCurrentEnvironment()
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      // 微信
      if (typeof options.code === 'undefined') {
        //如果没有code
        // 获取query对象
        const query = this.$route.query;
        // 获取等级id,所属商家
        this.levelPriceId = query.levelPriceId
        this.levelType = query.levelType
        this.shopId = query.shopId
        this.description = query.description
        this.type = query.type
        this.createOrder()
        this.$nextTick(() => {
          this.getWeiXinJsCode('snsapi_base')
        })

      } else {
        const query = this.$route.query;
        this.levelPriceId = query.levelPriceId
        this.levelType = query.levelType
        this.shopId = query.shopId
        this.description = query.description
        this.type = query.type
        this.order_no = query.order_no
        this.getOrderInfo(this.order_no);
        // 获取微信公众号的openid
        setTimeout(() => {
          this.getOpenid({
            provider: "wxpay",
            code: options.code
          });
        }, 300);
      }
    } else {
      //支付宝
      const query = this.$route.query;
      this.levelPriceId = query.levelPriceId
      this.levelType = query.levelType
      this.shopId = query.shopId
      this.description = query.description
      this.type = query.type
      this.createOrder()
    }
  },
  methods: {
    getCurrentEnvironment() {
      let ua = window.navigator.userAgent.toLowerCase();
      //判断是不是微信
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        // 微信
        this.currentEnvironment = "wx"
        this.payTypeName = "微信支付"
      }
      //判断是不是支付宝
      if (ua.match(/AlipayClient/i) == "alipayclient") {
        //支付宝
        this.currentEnvironment = "zfb"
        this.payTypeName = "支付宝支付"
      }
    },

    /**
     * 发起支付（唤起收银台，如果只有一种支付方式，则收银台不会弹出来，会直接使用此支付方式）
     * 在调用此api前，你应该先创建自己的业务系统订单，并获得订单号 order_no，把order_no当参数传给此api，而示例中为了简化跟支付插件无关的代码，这里直接已时间戳生成了order_no
     */
    open() {
      this.order_no = `shopLevel` + Date.now();
      this.out_trade_no = `${this.order_no}-1`;
      // 打开支付收银台
      this.$refs.pay.open({
        total_fee: this.total_fee, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
        order_no: this.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
        out_trade_no: this.out_trade_no, // 插件支付单号
        description: uni.getStorageSync('description'), // 支付描述
        type: uni.getStorageSync('type'), // 支付回调类型
        qr_code: this.qr_code, // 是否强制使用扫码支付
        openid: this.openid, // 微信公众号需要
        custom: this.custom, // 自定义数据（此参数不推荐使用，因为是前端传的，此参数可能会被伪造，建议通过order_no查询自己业务订单表来获取自定义业务数据）
      });
    },
    /**
     * 发起支付（不唤起收银台，手动指定支付方式）
     * 在调用此api前，你应该先创建自己的业务系统订单，并获得订单号 order_no，把order_no当参数传给此api，而示例中为了简化跟支付插件无关的代码，这里直接已时间戳生成了order_no
     */
    createOrder() {
      //根据levelPriceId 查看金额
      let self = this
      //搜索店铺
      $.ajax({
        url: API.getShopLevelPriceById,
        data: {
          "levelPriceId": self.levelPriceId
        },
        method: 'GET',
        success(res) {
          let umsShopLevelPrice = res.data.umsShopLevelPrice
          let umsShopLevel = res.data.umsShopLevel
          self.total_fee = umsShopLevelPrice.price * 100
          self.price_original = umsShopLevelPrice.priceOriginal * 100
          let timeType = umsShopLevelPrice.timeType;
          if (timeType === 1) {
            self.getLevelTimeTypeName = "一个月"
          } else if (timeType === 2) {
            self.getLevelTimeTypeName = "一季度"
          } else if (timeType === 3) {
            self.getLevelTimeTypeName = "一年"
          }
          self.getLevelTypeName = umsShopLevel.name
          self.custom = {
            "shopId": self.shopId,
            "levelPriceId": self.levelPriceId,
          }
          self.order_no = `shopLevel` + Date.now();
          self.out_trade_no = `${self.order_no}-1`;
          //将生成的订单插入到订单表
          let item = {
            payOrderNo: self.out_trade_no,
            orderNo: self.order_no,
            type: 4,
            shopId: self.shopId,
            totalPrice: self.total_fee,
            payPrice: self.total_fee,
            levelPriceId: self.levelPriceId,
          }
          self.addOrderInfo(item)
        }
      })
    },

    addOrderInfo(item) {
      $.ajax({
        url: API.addShopLevelOrder,
        data: {
          payOrderNo: item.payOrderNo,
          orderNo: item.orderNo,
          type: item.type,
          shopId: item.shopId,
          totalPrice: item.totalPrice,
          payPrice: item.payPrice,
          levelPriceId: item.levelPriceId
        },
        method: 'POST',
        loading: true,
        success(res) {
          uni.showToast({
            title: "订单创建成功",
            icon: "none"
          });
        }
      })
    },

    getOrderInfo(order_no) {
      //根据levelPriceId 查看金额
      let self = this
      //搜索店铺
      $.ajax({
        url: API.getByOrderNum,
        data: {
          "orderNo": order_no
        },
        method: 'GET',
        success(res) {
          let umsShopLevelPrice = res.data.umsShopLevelPrice
          let umsShopLevel = res.data.umsShopLevel
          self.total_fee = umsShopLevelPrice.price * 100
          self.price_original = umsShopLevelPrice.priceOriginal * 100
          let timeType = umsShopLevelPrice.timeType;
          if (timeType === 1) {
            self.getLevelTimeTypeName = "一个月"
          } else if (timeType === 2) {
            self.getLevelTimeTypeName = "一季度"
          } else if (timeType === 3) {
            self.getLevelTimeTypeName = "一年"
          }
          self.getLevelTypeName = umsShopLevel.name
          self.custom = {
            "shopId": self.shopId,
            "levelPriceId": self.levelPriceId,
          }
          self.order_no = res.data.orderNo;
          self.out_trade_no = res.data.payOrderNo;
        }
      })
    },

    toPay(provider) {
      let self = this
      // 发起支付
      self.$refs.pay.createOrder({
        provider: provider, // 支付供应商
        total_fee: self.total_fee, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
        order_no: self.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
        out_trade_no: self.out_trade_no, // 插件支付单号
        description: self.description, // 支付描述
        type: self.type, // 支付回调类型
        qr_code: false, // 是否强制使用扫码支付
        openid: self.openid, // 微信公众号需要
        custom: self.custom, // 自定义数据（此参数不推荐使用，因为是前端传的，此参数可能会被伪造，建议通过order_no查询自己业务订单表来获取自定义业务数据）
      });
    },
    /**
     * 生成支付独立二维码（只返回支付二维码）
     * 在调用此api前，你应该先创建自己的业务系统订单，并获得订单号 order_no，把order_no当参数传给此api，而示例中为了简化跟支付插件无关的代码，这里直接已时间戳生成了order_no
     */
    createQRcode(provider) {
      this.order_no = `shopLevel` + Date.now();
      this.out_trade_no = `${this.order_no}-1`;
      // 发起支付
      this.$refs.pay.createOrder({
        provider: provider, // 支付供应商
        total_fee: this.total_fee, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
        order_no: this.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
        out_trade_no: this.out_trade_no, // 插件支付单号
        description: this.description, // 支付描述
        type: this.type, // 支付回调类型
        qr_code: true, // 是否强制使用扫码支付
        cancel_popup: true, // 配合qr_code:true使用，是否只生成支付二维码，没有二维码弹窗
        openid: this.openid, // 微信公众号需要
        custom: this.custom, // 自定义数据（此参数不推荐使用，因为是前端传的，此参数可能会被伪造，建议通过order_no查询自己业务订单表来获取自定义业务数据）
      });
    },
    // 查询支付状态
    async getOrder() {
      let res = await this.$refs.pay.getOrder({
        out_trade_no: this.out_trade_no, // 插件支付单号
        await_notify: true
      });
      if (res) {
        let obj = {
          "-1": "已关闭",
          "1": "已支付",
          "0": "未支付",
          "2": "已部分退款",
          "3": "已全额退款"
        };
        uni.showToast({
          title: obj[res.status] || res.errMsg,
          icon: "none"
        });
      }
    },
    // 发起退款
    async refund() {
      let res = await this.$refs.pay.refund({
        out_trade_no: this.out_trade_no, // 插件支付单号
      });
      if (res) {
        uni.showToast({
          title: res.errMsg,
          icon: "none"
        });
      }
    },
    // 查询退款状态
    async getRefund() {
      let res = await this.$refs.pay.getRefund({
        out_trade_no: this.out_trade_no, // 插件支付单号
      });
      if (res) {
        uni.showModal({
          content: res.errMsg,
          showCancel: false
        });
      }
    },
    // 关闭订单
    async closeOrder() {
      let res = await this.$refs.pay.closeOrder({
        out_trade_no: this.out_trade_no, // 插件支付单号
      });
      if (res) {
        uni.showModal({
          content: res.errMsg,
          showCancel: false
        });
      }
    },
    // 获取公众号code
    async getWeiXinJsCode(scope = "snsapi_base") {
      let res = await this.$refs.pay.getProviderAppId({
        provider: "wxpay",
        provider_pay_type: "jsapi"
      });
      if (res.appid) {
        let appid = res.appid;
        let redirect_uri = encodeURIComponent(window.location.href.split("?")[0] + "?levelPriceId=" + this.levelPriceId + "&shopId=" + this.shopId + "&description=" + this.description + "&type=" + this.type + "&order_no=" + this.order_no + "&levelType=" + this.levelType);
        let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
        window.location.href = url;
      }

    },
    // 获取公众号openid
    async getOpenid(data) {
      let res = await this.$refs.pay.getOpenid(data);
      if (res) {
        this.openid = res.openid;
        uni.showToast({
          title: "已获取到openid，可以开始支付",
          icon: "none"
        });
      }
    },
    // 监听事件 - 支付订单创建成功（此时用户还未支付）
    onCreate(res) {
      console.log('create: ', res);
      // 如果只是想生成支付二维码，不需要组件自带的弹窗，则在这里可以获取到支付二维码 qr_code_image
    },
    // 监听事件 - 支付成功
    onSuccess(res) {
      console.log('success: ', res);
      if (res.user_order_success) {
        // 代表用户已付款，且你自己写的回调成功并正确执行了
        // 修改用户的商家的会员等级
        let self = this
        //搜索店铺
        $.ajax({
          url: API.updateShopLevel,
          data: {
            "type": self.levelType,
            "shopId": self.shopId,
            "shopLevelPriceId": self.levelPriceId
          },
          method: 'GET',
          success(res) {
            $.$toast('会员等级已生效，请前往电脑端查看');
          }
        })


      } else {
        // 代表用户已付款，但你自己写的回调执行成功（通常是因为你的回调代码有问题）

      }
    }
  },
  computed: {
    h5Env() {
      // #ifdef H5
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger' && (ua.match(/miniprogram/i) == 'miniprogram')) {
        // 微信小程序
        return "mp-weixin";
      }
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        // 微信公众号
        return "h5-weixin";
      }
      if (ua.match(/alipay/i) == 'alipay' && ua.match(/miniprogram/i) == 'miniprogram') {
        return "mp-alipay";
      }
      if (ua.match(/alipay/i) == 'alipay') {
        return "h5-alipay";
      }
      // 外部 H5
      return "h5";
      // #endif
    }
  },
}
</script>

<style lang="scss" scoped>
.app {
  padding: 30rpx;
}

input {
  border: 1px solid #f3f3f3;
  padding: 10rpx;
}

button {
  margin-top: 20rpx;
}

.label {
  margin: 10rpx 0;
}

.tips {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #565656;
}

</style>

<style lang="scss">
.pay-page {
  padding: 30rpx 30rpx 160rpx 30rpx;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;

  .address-box {
    padding: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 14rpx;
    background: #fff;
  }

  .address-text {
    font-size: 28rpx;
    color: #000;
    margin-left: 10rpx;
  }

  .shopping-box {
    margin-top: 20rpx;
    border-radius: 14rpx;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 20rpx 0;
  }

  .lable-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #000;
    padding: 10rpx 24rpx;
    border-bottom: 2rpx solid rgb(248, 248, 248);
  }

  .shopping-list {
    display: flex;
    flex-direction: column;
    padding: 0 24rpx;

  }

  .lable-number {
    font-size: 24rpx;
    color: #999;
    padding-right: 24rpx;
  }

  .shopping-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .shopping-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 2rpx solid rgb(248, 248, 248);
  }

  .shopping-img {
    height: 100rpx;
    width: 100rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .shopping-info {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
  }

  .shopping-hd {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .shopping-title {
    flex: 1;

  }

  .shopping-price {
    width: 120rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: rgb(245, 54, 22);
    font-size: 28rpx;
    font-weight: 600;
  }

  .shopping-text {
    margin-top: 10rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.end-price {
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.end-label {
  font-size: 24rpx;
  color: #000;
}

.end-number {
  color: rgb(245, 54, 22);
  font-size: 28rpx;
  font-weight: 600;
}

.footer-box {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 140rpx;
  background: #fff;
  display: flex;
  border-top: 1rpx solid rgb(214, 215, 217);

  .footer-content {
    padding: 24rpx;
    display: flex;
    align-items: center;
    // margin-bottom: 60rpx;
    flex: 1;
  }

  .price-box {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .price-text {
    display: flex;
    align-items: center;
    color: rgb(245, 54, 22);
    font-weight: 600;
    font-size: 32rpx;
  }
}

.print-item-entry {
  display: flex;
  align-items: center;
  // flex: 1;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.select-box {
  // width: 200rpx;
  display: flex;
  align-items: center;
  background: rgb(245, 54, 22);
  padding: 10rpx 30rpx;
  border-radius: 10rpx;
  margin-left: 20rpx;
  justify-content: center;

  .selecet-text {
    color: #fff;
    font-size: 24rpx;
  }

  .selecet-icon {
    margin-left: 4rpx;
  }
}

.cell-left {
  font-size: 24rpx;
  color: #000;
}

.cell-list {
  padding: 30rpx 24rpx;
  border-bottom: 1rpx solid rgb(214, 215, 217);

}
</style>